// AI对话功能核心实现
class ChatService {
    constructor() {
        this.API_URL = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
        this.API_KEY = '6eb6de30d0c6bab295e8730d7a8a71a0.gbET8XqExYOb99Ni';
        this.MODEL = 'glm-4v-plus-0111';
    }

    // 发送消息到AI并获取响应
    async sendMessage(message, messageHistory = []) {
        try {
            let content;
            if (typeof message === 'string' && message.startsWith('[图片] ')) {
                const imageUrl = message.replace('[图片] ', '');
                content = [
                    {
                        type: 'text',
                        text: '图里有什么'
                    },
                    {
                        type: 'image_url',
                        image_url: {
                            url: imageUrl
                        }
                    }
                ];
            } else {
                content = message;
            }

            const messages = [...messageHistory, {
                role: 'user',
                content: content
            }];

            console.log('发送给AI的内容:', messages);

            const response = await this.fetchAIResponse(messages);
            return response.choices[0].message;
        } catch (error) {
            console.error('发送消息失败:', error);
            throw new Error('与AI助手通信时出现错误，请稍后重试');
        }
    }

    // 调用AI API
    async fetchAIResponse(messages) {
        const payload = {
            model: this.MODEL,
            messages: messages
        };

        const response = await fetch(this.API_URL, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${this.API_KEY}`,
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    }
}

// 聊天界面管理
class ChatUI {
    constructor() {
        this.chatService = new ChatService();
        this.messageHistory = [];
        this.initializeUI();
    }

    initializeUI() {
        this.chatMessages = document.querySelector('.chat-messages');
        this.inputField = document.querySelector('.input-field');
        this.sendButton = document.querySelector('.send-button');

        // 绑定事件处理
        this.sendButton.addEventListener('click', () => this.handleSendMessage());
        this.inputField.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.handleSendMessage();
            }
        });
    }

    // 添加消息到界面
    addMessage(content, isUser = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isUser ? 'message-user' : 'message-ai'}`;
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';

        // 处理内容显示
        if (Array.isArray(content)) {
            content.forEach(item => {
                if (item.type === 'text') {
                    const textDiv = document.createElement('div');
                    textDiv.textContent = item.text;
                    contentDiv.appendChild(textDiv);
                } else if (item.type === 'image_url') {
                    const img = document.createElement('img');
                    img.src = item.image_url.url;
                    img.className = 'message-image';
                    img.style.maxWidth = '200px';
                    img.style.borderRadius = '8px';
                    contentDiv.appendChild(img);
                }
            });
        } else {
            contentDiv.textContent = content;
        }
        
        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.formatTime();
        
        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timeDiv);
        this.chatMessages.appendChild(messageDiv);
        
        this.scrollToBottom();
    }

    // 显示输入状态
    showTypingIndicator() {
        const typingDiv = document.createElement('div');
        typingDiv.className = 'typing-indicator';
        typingDiv.innerHTML = `
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
        `;
        this.chatMessages.appendChild(typingDiv);
        this.scrollToBottom();
        return typingDiv;
    }

    // 处理发送消息
    async handleSendMessage() {
        const message = this.inputField.value.trim();
        const fileUpload = window.fileUpload;
        const uploadedFiles = fileUpload.uploadedFiles;
        
        if (!message && uploadedFiles.length === 0) return;
        
        let content = [];
        
        if (message) {
            content.push({
                type: 'text',
                text: message
            });
        }
        
        uploadedFiles.forEach(imageUrl => {
            content.push({
                type: 'image_url',
                image_url: {
                    url: imageUrl
                }
            });
        });

        // 显示用户消息
        this.addMessage(content, true);
        
        // 清空输入和预览
        this.inputField.value = '';
        fileUpload.inputPreviewArea.innerHTML = '';
        fileUpload.uploadedFiles = [];

        // 更新消息历史
        this.messageHistory.push({
            role: 'user',
            content: content
        });

        // 显示AI正在输入状态
        const typingIndicator = this.showTypingIndicator();

        try {
            // 获取AI响应
            const response = await this.chatService.sendMessage(content, this.messageHistory);
            
            // 移除输入状态显示
            typingIndicator.remove();
            
            // 显示AI响应
            this.addMessage(response.content, false);
            
            // 更新消息历史
            this.messageHistory.push(response);
        } catch (error) {
            // 移除输入状态显示
            typingIndicator.remove();
            
            // 显示错误消息
            this.addMessage('抱歉，我遇到了一些问题。请稍后再试。', false);
            console.error('AI响应错误:', error);
        }
    }

    // 格式化时间
    formatTime() {
        const now = new Date();
        return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    }

    // 滚动到底部
    scrollToBottom() {
        this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
    }
}

// 文件上传相关功能
class FileUploadService {
    constructor() {
        this.initElements();
        this.initEventListeners();
        this.allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        this.maxFileSize = 10 * 1024 * 1024; // 10MB
        this.chatUI = window.chatUI;
        this.uploadedFiles = [];
    }

    initElements() {
        this.uploadTrigger = document.getElementById('upload-trigger');
        this.fileInput = document.getElementById('file-input');
        this.uploadPreview = document.querySelector('.upload-preview');
        this.previewImage = document.querySelector('.preview-image');
        this.previewVideo = document.querySelector('.preview-video');
        this.uploadProgress = document.querySelector('.upload-progress-bar');
        this.uploadStatus = document.querySelector('.upload-status');
        this.dropZone = document.querySelector('.drop-zone');
        this.fileError = document.querySelector('.file-error');
        this.inputPreviewArea = document.querySelector('.input-preview-area');
    }

    initEventListeners() {
        this.uploadTrigger.addEventListener('click', () => this.fileInput.click());
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        this.initDragAndDrop();
    }

    initDragAndDrop() {
        document.addEventListener('dragenter', (e) => {
            e.preventDefault();
            this.dropZone.classList.add('active');
        });

        document.addEventListener('dragover', (e) => {
            e.preventDefault();
        });

        document.addEventListener('dragleave', (e) => {
            e.preventDefault();
            if (e.target === this.dropZone) {
                this.dropZone.classList.remove('active');
            }
        });

        document.addEventListener('drop', (e) => {
            e.preventDefault();
            this.dropZone.classList.remove('active');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                this.handleFile(files[0]);
            }
        });
    }

    handleFileSelect(e) {
        const file = e.target.files[0];
        if (file) {
            this.handleFile(file);
        }
    }

    handleFile(file) {
        if (!this.allowedTypes.includes(file.type)) {
            this.showError('不支持的文件类型，请上传图片或视频文件');
            return;
        }

        if (file.size > this.maxFileSize) {
            this.showError('文件太大，请上传10MB以内的文件');
            return;
        }

        this.previewFile(file);
        this.uploadFile(file);
    }

    previewFile(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            this.uploadPreview.classList.add('active');
            if (file.type.startsWith('image/')) {
                this.previewImage.style.display = 'block';
                this.previewVideo.style.display = 'none';
                this.previewImage.src = e.target.result;
            } else if (file.type.startsWith('video/')) {
                this.previewImage.style.display = 'none';
                this.previewVideo.style.display = 'block';
                this.previewVideo.src = e.target.result;
            }
        };
        reader.readAsDataURL(file);
    }

    async uploadFile(file) {
        const formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch('http://39.98.54.173:8009/AI_chat/api/upload.php', {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                    'Access-Control-Allow-Origin': '*'
                },
                credentials: 'omit',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.error) {
                throw new Error(result.error);
            }

            // 模拟上传进度
            let progress = 0;
            const interval = setInterval(() => {
                progress += 5;
                if (progress <= 100) {
                    this.updateProgress(progress);
                } else {
                    clearInterval(interval);
                    this.uploadComplete(result);
                }
            }, 200);

        } catch (error) {
            console.error('文件上传失败:', error);
            this.showError(error.message || '文件上传失败，请重试');
        }
    }

    uploadComplete(result) {
        this.uploadStatus.textContent = '上传完成';
        setTimeout(() => {
            this.uploadPreview.classList.remove('active');
            this.uploadProgress.style.width = '0';
            this.fileInput.value = '';
        }, 1500);

        if (result && result.data && result.data.url) {
            const imageUrl = result.data.url;
            this.addPreviewThumbnail(imageUrl);
            this.uploadedFiles.push(imageUrl);
        }
    }

    addPreviewThumbnail(imageUrl) {
        const previewItem = document.createElement('div');
        previewItem.className = 'preview-item';
        
        const img = document.createElement('img');
        img.src = imageUrl;
        
        const removeButton = document.createElement('button');
        removeButton.className = 'remove-preview';
        removeButton.innerHTML = '<i class="fas fa-times"></i>';
        removeButton.onclick = () => {
            previewItem.remove();
            this.uploadedFiles = this.uploadedFiles.filter(url => url !== imageUrl);
        };
        
        previewItem.appendChild(img);
        previewItem.appendChild(removeButton);
        this.inputPreviewArea.appendChild(previewItem);
    }

    addImageMessage(imageUrl) {
        // 创建消息容器
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message message-user';
        
        // 创建消息内容容器
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        
        // 创建图片元素
        const img = document.createElement('img');
        img.src = imageUrl;
        img.className = 'message-image';
        img.style.maxWidth = '200px';
        img.style.borderRadius = '8px';
        
        // 添加图片到消息内容
        contentDiv.appendChild(img);
        
        // 创建时间标签
        const timeDiv = document.createElement('div');
        timeDiv.className = 'message-time';
        timeDiv.textContent = this.chatUI.formatTime();
        
        // 组装消息
        messageDiv.appendChild(contentDiv);
        messageDiv.appendChild(timeDiv);
        
        // 添加到聊天界面
        this.chatUI.chatMessages.appendChild(messageDiv);
        this.chatUI.scrollToBottom();

        // 发送图片URL给AI
        this.chatUI.handleSendMessage(`[图片] ${imageUrl}`);
    }

    updateProgress(progress) {
        this.uploadProgress.style.width = `${progress}%`;
        this.uploadStatus.textContent = `上传中 ${progress}%`;
    }

    showError(message) {
        this.fileError.textContent = message;
        this.fileError.classList.add('active');
        setTimeout(() => {
            this.fileError.classList.remove('active');
        }, 3000);
    }
}

// 初始化聊天界面和文件上传功能
document.addEventListener('DOMContentLoaded', () => {
    window.chatUI = new ChatUI();
    window.fileUpload = new FileUploadService();
});